package cn.modoumama.common.tools;

import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Iterator;
import java.util.Set;

public class ValidatorUtils {
    private static Validator validator;

    public ValidatorUtils() {
    }

    public static <T> Set<ConstraintViolation<T>> validate(T pojo, Class... clazz) {
        return validator.validate(pojo, clazz);
    }

    public static <T> void validateAndException(T pojo, Class... clazz) throws BindException {
        Set<ConstraintViolation<T>> constraintViolations = validate(pojo, clazz);
        if (constraintViolations != null && constraintViolations.size() > 0) {
            BindException e = new BindException(pojo, pojo.getClass().getSimpleName());
            Iterator var4 = constraintViolations.iterator();

            while(var4.hasNext()) {
                ConstraintViolation<T> error = (ConstraintViolation)var4.next();
                FieldError fieldError = new FieldError(pojo.getClass().getSimpleName(), error.getPropertyPath().toString(), error.getMessage());
                e.addError(fieldError);
            }

            throw e;
        }
    }

    static {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        validator = factory.getValidator();
    }
}
